package com.nnnu.wsnackshop.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.nnnu.wsnackshop.pojo.entity.OrderItems;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.math.BigDecimal;

/**
 * <p>
 * 订单明细 Mapper 接口
 * </p>
 *
 * @author zk
 * @since 2025-05-14
 */
@Mapper
public interface OrderItemsMapper extends BaseMapper<OrderItems> {

        /**
         * 获取商品总销量
         * 
         * @param productId 商品ID
         * @return 销量总数
         */
        @Select("SELECT SUM(oi.quantity) FROM order_items oi " +
                        "JOIN orders o ON oi.order_id = o.id " +
                        "WHERE oi.product_id = #{productId} AND o.order_status = 4")
        Integer getTotalSalesByProduct(@Param("productId") Integer productId);

        /**
         * 获取商品总收入
         * 
         * @param productId 商品ID
         * @return 总收入金额
         */
        @Select("SELECT SUM(oi.subtotal) FROM order_items oi " +
                        "JOIN orders o ON oi.order_id = o.id " +
                        "WHERE oi.product_id = #{productId} AND o.order_status = 4")
        BigDecimal getTotalRevenueByProduct(@Param("productId") Integer productId);

        /**
         * 获取商品销量（只计算已完成订单）
         * 
         * @param productId 商品ID
         * @return 销量
         */
        @Select("SELECT IFNULL(SUM(oi.quantity), 0) FROM order_items oi " +
                        "JOIN orders o ON oi.order_id = o.id " +
                        "WHERE oi.product_id = #{productId} AND o.order_status = 4")
        Integer getProductSales(@Param("productId") Integer productId);
}
